import React from "react";
import store, { RootState } from "../../store";
import { useSelector, useDispatch } from "react-redux";
import { Checkbox, Stepper, SubmitBar } from "react-vant";
import { useNavigate } from "react-router-dom";

const Index: React.FC = () => {
  // 1. 获取仓库数据  cartList
  const cartList = useSelector((state: RootState) => state.cart.cartList);
  // 2. 获取dispatch
  const dispatch = useDispatch();
  const navigate = useNavigate()
  // 3. 购物车总价
  const totalPrice = cartList
    .filter((v) => v.state)
    .reduce((p, n) => p + n.count * n.price, 0);
  return (
    <div>
      <div className="cart-list">
        {cartList.map((v, i) => {
          return (
            <div className="cart-item" key={i}>
              <Checkbox
                checked={v.state}
                className="checkbox"
                onChange={() => {
                  dispatch({ type: "changeState", payload: v });
                }}
              ></Checkbox>
              <img src={v.image} alt="" />
              <div className="right">
                <div className="title">{v.title}</div>
                <div className="desc" style={{ fontSize: 12 }}>
                  {v.desc}
                </div>
                <div className="count">
                  <Stepper
                    // min={1}
                    value={v.count}
                    onPlus={() => {
                      dispatch({ type: "addCart", payload: v });
                    }}
                    onMinus={() => {
                      if (v.count > 1)
                        dispatch({ type: "subCart", payload: v });
                    }}
                  ></Stepper>
                </div>
                <div className="price">{v.price}</div>
              </div>
            </div>
          );
        })}
      </div>
      <SubmitBar
        price={totalPrice * 100}
        buttonText="提交订单"
        onSubmit={() => {
          // navigate('/order?price=' + totalPrice)
          
          // navigate('/order', {
          //   state: totalPrice
          // })

          navigate(`/order/${totalPrice}`)
          
        }}
      >
        <Checkbox>全选</Checkbox>
      </SubmitBar>
    </div>
  );
};

export default Index;
